package com.gy.mbaselibrary.views.carous;

import android.content.Context;
import android.os.Handler;
import android.os.Message;
import android.util.AttributeSet;
import android.view.MotionEvent;

import androidx.viewpager.widget.ViewPager;

/**
 * Created by Administrator on 2017/6/9.
 */

public class CarouselViewPager extends ViewPager {
    public static final int RESUME = 0;
    public static final int PAUSE = 1;
    public static final int DESTROY = 2;
    /**
     * 切换时间
     */
    private int delayTime = 3000;
    private boolean canPlay = true;

    public CarouselViewPager(Context context) {
        super(context);
    }

    public CarouselViewPager(Context context, AttributeSet attrs) {
        super(context, attrs);
    }


    @Override
    public boolean onTouchEvent(MotionEvent ev) {
        switch (ev.getAction()) {
            case MotionEvent.ACTION_DOWN:
            case MotionEvent.ACTION_MOVE:
                canPlay = false;
                break;
            case MotionEvent.ACTION_CANCEL:
            case MotionEvent.ACTION_UP:
            case MotionEvent.ACTION_OUTSIDE:
                canPlay = true;
                break;
        }
        return super.onTouchEvent(ev);
    }

    @Override
    public void setCurrentItem(int item) {
        if (canPlay)
        super.setCurrentItem(item,true);
    }

    private Handler mChangeHandler = new Handler(){
        @Override
        public void handleMessage(Message msg) {
            super.handleMessage(msg);
            if (getAdapter() != null)
                if (getAdapter().getCount() > 1){
                    setCurrentItem(getCurrentItem() + 1);
                    mChangeHandler.sendEmptyMessageDelayed(0,delayTime);
                }
        }
    };

    private void startTimer(){
        mChangeHandler.sendEmptyMessageDelayed(0,delayTime);
    }

    private void stopTimer(){
        mChangeHandler.removeMessages(0);
    }

    public void destroy(){
        stopTimer();
    }

    public void resume(){
        canPlay = true;
        startTimer();
    }

    public void pause(){
        canPlay = false;
        stopTimer();
    }

    public void setDelay(int delayTime) {
        this.delayTime = delayTime;
    }
}
